<?php

namespace App\Handlers;

use Gregwar\Captcha\CaptchaBuilder;

class GregwarHandler
{ //生成验证码
    public function captcha()
    {
        $captchaBuilder = new CaptchaBuilder;

        //$key = 'captcha-'.str_random(15);

        $captcha = $captchaBuilder->build();

        $expiredAt = now()->addMinutes(2);

        //\Cache::put($key, ['phone' => $phone, 'code' => $captcha->getPhrase()], $expiredAt);
        \Cache::put('code' . $captcha->getPhrase(), $captcha->getPhrase(), $expiredAt);

        $img_name = md5(time()) . '.jpg';

        $date = date('Ymd', time());

        if(!file_exists(public_path().'/uploads/images/gregwar/'.$date)){

            mkdir(public_path().'/uploads/images/gregwar/'.$date,0777);
        }

        $save_psth=public_path().'/uploads/images/gregwar/'.$date.'/'.$img_name;

        $base64_string = explode(',', $captcha->inline());

        file_put_contents($save_psth, base64_decode($base64_string[1]));

        $result = [
            'code' => $captcha->getPhrase(),
            //'captcha_key' => $key,
            'expired_at' => $expiredAt->toDateTimeString(),
            // 'captcha_image_content' => $captcha->inline()
            'url' => config('app.url') . '/uploads/images/gregwar/' . $date . '/' . $img_name,
        ];

        return $result;
    }

    /*
    public function verifySmsCode($code)
    {
        $key = 'code' . $code;

        if ($res = \Cache::get($key)) {

            \Cache::forget($key);

            return true;
        } else {

            return false;

        }
    }
    */
}
